const { ErrorModel, SuccessModel } = require('./../utils/index')
const logger = require('./../utils/logger')
const { MySQL } = require('./../utils/Mysqldb');
const { PostgreSQL } = require('./../utils/Postgredb');
const { Oracle } = require('./../utils/Oracledb');
const { DataSourceModel } = require("./../models/data_source")
class DataSourceController {
  /**
   * @description 测试数据源
   * @param {*} name
   * @param {*} db_type
   * @param {*} host
   * @param {*} port
   * @param {*} db_name
   * @param {*} user
   * @param {*} password
   */
  static async dataSourceCheck (req, res, next) {
    const { name, db_type, host, port, db_name, user, password } = req.body
    logger.info(`DataSourceController`, `dataSourceCheck`, `req.body`, req.body)
    if (!name) {
      res.json(new ErrorModel([], `请输入数据源名称`))
      return
    }
    try {
      switch (db_type) {
        case "MySQL":
          const mysqlInfo = {
            host: host,
            port: port,                 // 连接端口
            user: user,
            password: password,
            database: db_name,
          }
          MySQL.connect(mysqlInfo).then(async (mysqlConfig) => {
            await MySQL.close(mysqlConfig);
            res.json(new SuccessModel([], `连接成功`));
          }).catch(err => {
            logger.error(`DataSourceController`, `dataSourceCheck`, `error`, err)
            res.json(new ErrorModel([], err.message))
          })
          break;
        case "PostgreSQL":
          const pgInfo = {
            host: host,        // 数据库所在IP
            user: user,           // 数据库用户名
            database: db_name,       // 数据库
            password: password,       // 数据库密码
            port: port                 // 连接端口
          };
          PostgreSQL.connect(pgInfo).then((pgConfig) => {
            res.json(new SuccessModel([], `连接成功`));
            pgConfig.close()
          }).catch(err => {
            logger.error(`DataSourceController`, `dataSourceCheck`, `error`, err)
            res.json(new ErrorModel([], err.message))
          })
          break;
        case "Oracle":
          const oracleInfo = {
            user: user,　　//用户名
            password: password,　　//密码
            connectString: `${host}:${port}/${db_name}`,
          };
          Oracle.connect(oracleInfo).then((oracleConfig) => {
            res.json(new SuccessModel([], `连接成功`));
            oracleConfig.close()
          }).catch(err => {
            logger.error(`DataSourceController`, `dataSourceCheck`, `error`, err)
            res.json(new ErrorModel([], err.message))
          })
          break;
        default:
          res.json(new ErrorModel([], "暂不支持此类型数据库"))
          break;
      }
    } catch (error) {
      logger.error(`DataSourceController`, `dataSourceCheck`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 添加数据源
   * @param {*} name
   * @param {*} db_type
   * @param {*} host
   * @param {*} port
   * @param {*} db_name
   * @param {*} user
   * @param {*} password
   */
  static async dataSourceAdd (req, res, next) {
    const { name, db_type, host, port, db_name, user, password, remark } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`DataSourceController`, `dataSourceAdd`, `req.body`, req.body)
    if (!name) {
      res.json(new ErrorModel([], `请输入数据源名称`))
      return
    }
    try {
      const sourceInfo = await DataSourceModel.findByName(name)
      if (sourceInfo) {
        res.json(new ErrorModel([], `当前数据源已存在`))
        return
      }
      const result = await DataSourceModel.create(name, db_type, host, port, db_name, user, password, remark, op_user_id,)
      logger.info(`DataSourceController`, `dataSourceAdd`, `result`, result)
      res.json(new SuccessModel([], `新增数据源成功`))
    } catch (error) {
      logger.error(`DataSourceController`, `dataSourceAdd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 更新数据源
   * @param {*} data_source_id
   * @param {*} name
   * @param {*} db_type
   * @param {*} host
   * @param {*} port
   * @param {*} db_name
   * @param {*} user
   * @param {*} password
   */
  static async dataSourceUpd (req, res, next) {
    const {
      data_source_id,
      name,
      db_type,
      host,
      port,
      db_name,
      user,
      password,
      remark,
    } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`DataSourceController`, `dataSourceUpd`, `req.body`, req.body)
    if (!data_source_id || !name) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const sourceInfo = await DataSourceModel.findByNameAndId(name, data_source_id)
      if (sourceInfo) {
        res.json(new ErrorModel([], `数据源已存在`))
        return
      }
      const result = await DataSourceModel.update(name, db_type, host, port, db_name, user, password, remark, op_user_id, data_source_id)
      logger.info(`DataSourceController`, `dataSourceUpd`, `result`, result)
      res.json(new SuccessModel([], `数据源更新成功`))
    } catch (error) {
      logger.error(`DataSourceController`, `dataSourceUpd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除数据源
   * @param {*} data_source_id
   */
  static async dataSourceDel (req, res, next) {
    const { data_source_id } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`DataSourceController`, `dataSourceDel`, `req.body`, req.body)
    if (!data_source_id) {
      res.json(new ErrorModel([], `data_source_id 获取失败`))
      return
    }
    try {
      const result = await DataSourceModel.delete(op_user_id, data_source_id)
      logger.info(`DataSourceController`, `dataSourceDel`, `result`, result)
      res.json(new SuccessModel([], `删除数据源成功`))
    } catch (error) {
      logger.error(`DataSourceController`, `dataSourceDel`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 数据源分页列表
   * @param {*} data_source_id
   */
  static async dataSourceList (req, res, next) {
    const {
      limit,
      size = 1,
      name,
      db_type,
      host,
      db_name,
      remark,
    } = req.query
    logger.info(
      `DataSourceController`,
      `dataSourceList`,
      `req.query`,
      req.query
    )
    try {
      const { result, count } = await DataSourceModel.list(Number(limit), Number(size), name, db_type, host, db_name, remark,)
      logger.info(`DataSourceController`, `dataSourceList`, `result`, result, count)
      res.json(new SuccessModel({ result, total: count[0].count, limit: Number(limit), size: Number(size) }, `获取数据源数据成功`))
    } catch (error) {
      logger.error(`DataSourceController`, `dataSourceList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 数据源all
   * @param {*} data_source_id
   */
  static async dataSourceALL (req, res, next) {
    try {
      const result = await DataSourceModel.allList();
      logger.info(`DataSourceController`, `dataSourceALL`, `result`, result,)
      res.json(new SuccessModel({ result, }, `获取数据源数据成功`))
    } catch (error) {
      logger.error(`DataSourceController`, `dataSourceALL`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
}

module.exports = {
  DataSourceController,
}
